'''
BaiduTrans V1.0
By SkyFire
QQ:1513008876
E-Mail:skyfireitdiy@hotmail.com
'''

import httplib2
from urllib.parse import urlencode
import json


class BaiduTrans:
    __g_http_client = httplib2.Http('.Cache')

    '''
    Init
    '''
    def __init__(self):
        pass

    def get_lang_type(self,text):
        '''
        获取语言类型
        :param text:要判断的文字
        :return:判断结果:如 'zh'表示中文  'en'表示英文 ,如果发生错误,返回''
        '''
        text=text[:16]
        data={'query':text}
        try:
            response,content=self.__g_http_client.request('http://fanyi.baidu.com/langdetect','POST',urlencode(data),
                                                          headers={'Content-Type': 'application/x-www-form-urlencoded'})
            if response['status']=='200':
                content=content.decode('utf-8')
                ret_data=json.loads(content)
                if ret_data['error']==0:
                    return  ret_data['lan']
                else:
                    return ''
            else:
                return ''
        except:
            return ''

    def translate(self,text,src_lan=None,dest_lan='zh'):
        '''
        翻译
        :param text: 要翻译的文字
        :param src_lan: 源语言
        :param dest_lan:目标语言
        :return: 如果成功,返回翻译后的文字,否则,返回源文字
        '''
        if src_lan==None:
            src_lan=self.get_lang_type(text)
        if dest_lan==src_lan:
            if dest_lan=='zh':
                dest_lan='en'
            else:
                dest_lan='zh'
        if len(text)>1500:
            text=text[:1500]
        data={'from':src_lan,'to':dest_lan,'query':text,'transtype':'realtime','simple_means_flag':3}
        try:
            response, content = self.__g_http_client.request('http://fanyi.baidu.com/v2transapi', 'POST',
                                                             urlencode(data), headers={
                    'Content-Type': 'application/x-www-form-urlencoded'})
            if response['status'] == '200':
                content = content.decode('utf-8')
                ret_data = json.loads(content)
                return ret_data['trans_result']['data'][0]['dst']
            else:
                return text
        except:
            return text


if __name__=='__main__':
    trans=BaiduTrans()
    text=input('Text:')
    print(trans.translate(text))
